using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Security;
using System.IO;
using TestWeb.Models;
using TestWeb.Repositories;
using TestWeb.Helpers;

namespace TestWeb.Controllers
{	
	/// <summary>
	/// The partial of AdminController to manage NguoiDung
	/// </summary>
	public partial class AdminController : BaseController
	{
		#region Methods

		/// <summary>
		/// The action for selecting range of elements in the table NguoiDung 
		/// </summary>
		/// <param name="Role">The role of current active user</param>
		/// <param name="Page">The page which user want to go to</param>
		/// <returns>Result of an action method</returns>
		public ActionResult SelectNguoiDung(string Role, int Page = 1)
		{
			var viewModel = new ViewModel
			{
				NguoiDungs = this.RepNguoiDung.Select(Role, Page)
			};
			this.UpdateModel(viewModel);

            ViewData["PartialRequest"] = "List";
			ViewData["CurrentPage"] = Page;
			ViewData["TotalPage"] = this.RepNguoiDung.TotalPages;
			
			return View("SelectNguoiDung", viewModel);
		}

		/// <summary>
		/// The action for selecting a specified element in table NguoiDung
		/// </summary>
        /// <param name="ID">The key for identifying the element</param>
		/// <returns>Result of an action method</returns>
		public ActionResult DetailOfNguoiDung(Guid ID)
		{
			var viewModel = new ViewModel
			{
				NguoiDungs = new List<NguoiDungModel>() { this.RepNguoiDung.SelectByID(ID) }
			};
			this.UpdateModel(viewModel);

            return PartialView("Partials/Prt_NguoiDung_Detail", viewModel.NguoiDungs.Count > 0 ? viewModel.NguoiDungs[0] : null);
		}

		/// <summary>
		/// The action to delete an element in table NguoiDung 
		/// </summary>
		/// <param name="ID">The key for identifying the element will be deleted</param>
		/// <returns>Result of an action method</returns>
		[AcceptVerbs(HttpVerbs.Delete)]
		public JsonResult DeleteNguoiDung(Guid ID)
		{
			var msgTxt = string.Empty;
			var result = this.RepNguoiDung.Delete(ID, ref msgTxt);
			
			return Json(new{
				Success = result,
				MsgTxt = result ? string.Format("The specified item with ID = {0} has been deleted", ID) : msgTxt,
				DeleteId = ID
			});
		}

        /// <summary>
        /// The action for editting an element in table NguoiDung 
        /// </summary>
        /// <param name="ID">The key for identifying the element will be edited</param>
        /// <param name="Role">The role of current active user</param>
        /// <param name="CurrentPage">The current page</param>
        /// <returns>Result of an action method</returns>
        public ActionResult EditNguoiDung(Guid ID, string Role, int CurrentPage = 1)
        {
            var viewModel = new ViewModel
            {
                NguoiDungs = this.RepNguoiDung.SelectToPage(Role, CurrentPage)
            };
            this.UpdateModel(viewModel);

            ViewData["CurrentPage"] = CurrentPage;
            ViewData["TotalPage"] = this.RepNguoiDung.TotalPages;
            ViewData["EditItem"] = ID;

            return PartialView("Partials/Prt_NguoiDung_Edit", viewModel);
        }

        /// <summary>
        /// The action to cancel for editting an element in table NguoiDung 
        /// </summary>
        /// <param name="Role">The role of current active user</param>
        /// <param name="CurrentPage">The current page</param>
        /// <returns>Result of an action method</returns>
        public ActionResult CancelEditingNguoiDung(string Role, int CurrentPage = 1)
        {
            var viewModel = new ViewModel
            {
                NguoiDungs = this.RepNguoiDung.SelectToPage(Role, CurrentPage)
            };
            this.UpdateModel(viewModel);

            ViewData["CurrentPage"] = CurrentPage;
            ViewData["TotalPage"] = this.RepNguoiDung.TotalPages;

            return PartialView("Partials/Prt_NguoiDung_List", viewModel);
        }

		/// <summary>
		/// The action to update an element in table NguoiDung 
		/// </summary>
		/// <param name="Forms">The collection parameters retrieved from Views</param>
		/// <returns>Result of an action method</returns>
		[ValidateInput(false)]
		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult UpdateNguoiDung(FormCollection Forms)
		{
			var msgTxt = string.Empty;
			var Role = Forms.GetValues("Role")[0];
			var CurrentPage = int.Parse(Forms.GetValues("CurrentPage")[0]);
			var iD = Forms.GetValues("ID")[0];
            var isEnable = bool.Parse(Forms.GetValues("IsEnable")[0]);

            // For the admin page, just update Enable attribute of user
			var item = this.RepNguoiDung.SelectByID(Guid.Parse(iD));
            item.IsEnable = isEnable;
      
			var result = this.RepNguoiDung.Update(item, ref msgTxt);
      
			var viewModel = new ViewModel
			{
				NguoiDungs = this.RepNguoiDung.SelectToPage(Role, CurrentPage)
			};
			this.UpdateModel(viewModel);

            ViewData["PartialRequest"] = "List";
			ViewData["CurrentPage"] = CurrentPage;
			ViewData["TotalPage"] = this.RepNguoiDung.TotalPages;
			ViewData["MsgTxt"] = result ? string.Format("The record with ID = {0} has been updated.", item.NguoiDung.ID) : msgTxt;
      
			return View("SelectNguoiDung", viewModel);
		}

		/// <summary>
		/// The action to insert an element in table NguoiDung 
		/// </summary>
		/// <param name="Forms">The collection parameters retrieved from Views</param>
		/// <returns>Result of an action method</returns>
		[ValidateInput(false)]
		[AcceptVerbs(HttpVerbs.Post)]
		public ActionResult InsertNguoiDung(FormCollection Forms)
		{
			var msgTxt = string.Empty;
			var userName = Forms.GetValues("UserName")[0];
			var password = Forms.GetValues("Password")[0];
			var email = Forms.GetValues("Email")[0];
			var role = Forms.GetValues("Role")[0];
			
			var item = new NguoiDungModel
			{
				UserName = userName,
				Password = password,
				Email = email,
				Role = role,
				NguoiDung = new NguoiDung()
			};
      
			var result = this.RepNguoiDung.Insert(item, ref msgTxt);
			
			var viewModel = new ViewModel
			{
			};
			this.UpdateModel(viewModel);

            ViewData["PartialRequest"] = "Insert";
            ViewData["Result"] = result;
            ViewData["MsgTxt"] = result ? string.Format("The new record with ID = {0} has been added.", item.NguoiDung.ID) : msgTxt;
			
			return View("SelectNguoiDung", viewModel);
		}

        /// <summary>
        /// The action to navigate to the form for inserting new record
        /// </summary>
        /// <returns>Result of an action method</returns>
        public ActionResult EnterInsertNguoiDung()
        {
            var viewModel = new ViewModel
            {
            };
            this.UpdateModel(viewModel);

            ViewData["PartialRequest"] = "Insert";
            return View("SelectNguoiDung", viewModel);
        }

        /// <summary>
        /// The action to navigate to the form for deletting a range of records
        /// </summary>
        /// <param name="Role">The role of current active user</param>
        /// <param name="Page">The page which user want to go to</param>
        /// <returns>Result of an action method</returns>
        public ActionResult EnterDeleteRangeOfNguoiDung(string Role, int Page = 1)
        {
            var viewModel = new ViewModel
            {
                NguoiDungs = this.RepNguoiDung.Select(Role, Page)
            };
            this.UpdateModel(viewModel);

            ViewData["PartialRequest"] = "Delete";
            ViewData["CurrentPage"] = Page;
            ViewData["TotalPage"] = this.RepNguoiDung.TotalPages;
            return View("SelectNguoiDung", viewModel);
        }

        /// <summary>
        /// The action to execute deleting one or multiple record in database 
        /// </summary>
        /// <param name="Forms"></param>
        /// <returns></returns>
        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult DeleteRangeOfNguoiDung(FormCollection Forms)
        {
            var msgTxt = string.Empty;
            var result = false;
            var CurrentPage = 1;
            var numItemToBeDeleted = 0;
            var numItemDeleted = 0;

            var items = Forms.GetValues("MaNguoiDungs")[0];
            var Role = Forms.GetValues("Role")[0];
            var itemsToDelete = items.Split(new char[] { ';' });

            foreach (string id in itemsToDelete)
            {
                if (!id.Equals(string.Empty))
                {
                    numItemToBeDeleted++;
                    result = this.RepNguoiDung.Delete(Guid.Parse(id), ref msgTxt);
                    if (result)
                        numItemDeleted++;
                }
            }
            var viewModel = new ViewModel
            {
                NguoiDungs = this.RepNguoiDung.SelectToPage(Role, CurrentPage)
            };
            this.UpdateModel(viewModel);

            // Get result 
            result = numItemToBeDeleted == numItemDeleted ? true : false;

            if (result)
                msgTxt = string.Format("All of the selected records (The number of records = {0}) have been deleted", numItemToBeDeleted);
            else
                msgTxt = string.Format("The number of records to be deleted = {0}, and the number of records have been deleted = {1}", numItemToBeDeleted, numItemDeleted);

            ViewData["PartialRequest"] = "Delete";
            ViewData["CurrentPage"] = CurrentPage;
            ViewData["TotalPage"] = this.RepNguoiDung.TotalPages;
            ViewData["Result"] = result;
            ViewData["MsgTxt"] = msgTxt;

            return View("SelectNguoiDung", viewModel);
        }

		#endregion

	}
}
